package com.example.PriceCompare;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SearchResult extends Activity{
	
	private ListView ResultListView;
	private ArrayList<Entry> arrayResultList;
	private Entry TempEntry;
	private BaseAdapter resultAdapter;
    private Cursor cursor;
    private String[] allDesc;
    private int[] allPrice;
    private String[] allPhone;
    private String[] allAddress;
    private String SearchKey;
    private double Dist;
    private int count=0;
    private int i=0;
    private int flag2=0;
    private Address address;
    private double CurLat, CurLong;
    private double allDistance[];
    public DatabaseAdapter mDbHelper;
    private InputStream is;
    private String result;
    private double tempdist;
    
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.displaysearchresult);
	        Bundle bundle = this.getIntent().getExtras();
	        CurLat=bundle.getDouble("lat");
	        CurLong=bundle.getDouble("long");
	        Dist=bundle.getDouble("distance");
	        SearchKey=bundle.getString("searchkey");
			Log.d("test",Double.toString(CurLat));
			arrayResultList = new ArrayList<Entry>();
/*			mDbHelper = new DatabaseAdapter(this);
			mDbHelper.open();
			cursor = mDbHelper.getAllItems();
			startManagingCursor(cursor);
			Log.i("ret",cursor.getCount()+"");
			if(cursor.moveToFirst()){
				Log.i("imp","empty");
			}
			String tag = new String("as");
			allDesc = new String[5000];
			allAddress = new String[5000];
			allPhone = new String[5000];
			allPrice = new int[5000];
			allDistance = new double[5000];

			do{
				Log.i("imp", count+"");
//				if((cursor.getString(2)).indexOf(SearchKey)!=-1)
				{
			    allAddress[count]= cursor.getString(1);
			    allDesc[count]= cursor.getString(2);
			    allPrice[count]= cursor.getInt(3);
			    allPhone[count] = cursor.getString(4);
			    allDistance[count]=mapThisLocation(allAddress[count]);
			    count++;}
			}while(cursor.moveToNext());
			Log.i("chk",allPhone[0]);*/
	
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("name",SearchKey));
	        

	        
	        try{
	                HttpClient httpclient = new DefaultHttpClient();
	                HttpPost httppost = new HttpPost("http://10.1.8.14/pricecompare.php");
	                
	                Log.d("before", "ch1");
	                
	                
	                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	                HttpResponse response = httpclient.execute(httppost); 
	                HttpEntity entity = response.getEntity();
	                is = entity.getContent();
	                Log.e("log_tag", "connection success ");
	                //Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	        }catch(Exception e){
	                Log.e("log_tag", "Error in http connection "+e.toString());
	                Toast.makeText(getApplicationContext(), "error in http connection", Toast.LENGTH_SHORT).show();

	        }
	        Log.d("after", "ch1");
	        //convert response to string
	        try{
	                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	                StringBuilder sb = new StringBuilder();
	                String line = null;
	                while ((line = reader.readLine()) != null) {
	                        sb.append(line + "\n");
//	                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	                }
	                is.close();

	                result=sb.toString();
	        }catch(Exception e){
	               Log.e("log_tag", "Error converting result "+e.toString());
	            Toast.makeText(getApplicationContext(), "Error converting result", Toast.LENGTH_SHORT).show();

	        }
	        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                       JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","fname: "+json_data.getString("name"));
                        //txtview.setText(json_data.getString("fname"));
//                        Toast.makeText(getApplicationContext(), "pass2"+json_data.getString("name"), Toast.LENGTH_SHORT).show();
                        tempdist=mapThisLocation(json_data.getString("address"));
                        if(tempdist<=Dist){

            	        	TempEntry = new Entry(json_data.getString("name"),json_data.getString("address"), json_data.getInt("price"),tempdist,json_data.getString("phone"));
            		        arrayResultList.add(TempEntry);	
                        }                        
               }

        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
                Toast.makeText(getApplicationContext(), "fail2", Toast.LENGTH_SHORT).show();
        }
			
			
/*			
	        for(i=0;i<count;i++)
	        {
	        	if(allDistance[i]<=Dist)
	        	{
	        	TempEntry = new Entry(allDesc[i],allAddress[i], allPrice[i],allDistance[i]);
		        arrayResultList.add(TempEntry);
	        	}
	        }
*/			
	        ResultListView = (ListView) findViewById(R.id.ListView01);
	        resultAdapter = new ResultAdapter(this,arrayResultList);
	        ResultListView.setAdapter(resultAdapter);
	        //ResultListView.
	        ViewInit();
	 }
	private void ViewInit(){
		
		ResultListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				//				Toast.makeText(getApplicationContext(), "List clicked"+position, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(getApplicationContext(),DisplayInfo.class);
				Bundle bundle = new Bundle();
				bundle.putString("name", arrayResultList.get(position).getProductName());
				bundle.putString("store", arrayResultList.get(position).getStoreAddress());
				bundle.putString("phone", arrayResultList.get(position).getStorePhoneNumber());
				bundle.putInt("price", arrayResultList.get(position).getPrice());
				bundle.putDouble("distance", arrayResultList.get(position).getDistance());
				bundle.putDouble("fromlat",CurLat);
				bundle.putDouble("fromlong",CurLong);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		
	}
	
	
	protected double mapThisLocation(String tostring){
		Geocoder g = new Geocoder(this);
		List<Address> addresses;

		try {
//			do{
			addresses=g.getFromLocationName(tostring, 1);
			Log.i("tag", "errorcode3");
//			}while(addresses.size()<=0);
			  Log.i("dist","---->"+addresses.size()+"");
			if(addresses.size()>0){
				
				address=addresses.get(0);
				address.getLatitude();
				address.getLongitude();
				return(distance(address.getLatitude(),address.getLongitude(), CurLat, CurLong));

			}
			else{
//				Toast.makeText(this, "We Failed to Locate Destination", Toast.LENGTH_SHORT).show();
				flag2=0;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			Toast.makeText(this, "No idea!!!", Toast.LENGTH_SHORT).show();
			flag2=0;
		}
		return 100000.0;
		
	}
	
	private double distance(double lat1, double lon1, double lat2, double lon2) {

		  double theta = lon1 - lon2;
		  double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
		  
		  dist = Math.acos(dist);
		  dist = rad2deg(dist);
		  dist = dist * 60 * 1.1515;
		  dist = dist * 1.609344;
		  
		  Log.i("test","lat2-"+lat2+"long2-"+lon2+dist+"");
		  return ((double)((int)((dist+0.05)*10.0))/10.0);
		}
	
	private double deg2rad(double deg) {
		  return (deg * Math.PI / 180.0);
		}
	
	private double rad2deg(double rad) {
		  return (rad * 180.0 / Math.PI);
		}
	

	
	 
}


